package demo.hdz.testui;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;

/**
 * @author hdz
 * @date 2018/07/04
 */
public class ShowHideActivityService extends Service {
    private LocalBinder binder = new LocalBinder();
    private MainActivity mMainActivity;

    /**
     * 发送广播隐藏Activity
     * adb shell am broadcast -a demo.hdz.testui.action --ei demo.hdz.testui.cmd 0
     *
     * 发送广播显示Activity
     * adb shell am broadcast -a demo.hdz.testui.action --ei demo.hdz.testui.cmd 1
     * */


    BroadcastReceiver broadcastReceiver0 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constant.BROADCAST_ACTION)) {
                int cmd = intent.getIntExtra(Constant.BROADCAST_EXTRA, 0) ;
                if (cmd == Constant.CMD_ACTIVITY_SHOW) {
                    Intent intent1 = new Intent(ShowHideActivityService.this, MainActivity.class);
                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent1);
                } else if (cmd == Constant.CMD_ACTIVITY_HIDE){
                    mMainActivity.onBackPressed();
                }
            }
        }
    };

    public ShowHideActivityService() {
    }

    public class LocalBinder extends Binder {
        ShowHideActivityService getService() {
            return ShowHideActivityService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        registerReceiver(broadcastReceiver0, new IntentFilter(Constant.BROADCAST_ACTION));
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(broadcastReceiver0);
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    public void setMainActivity(MainActivity mainActivity) {
        this.mMainActivity = mainActivity;
    }
}
